// src/utils/loading.ts
import { createApp } from "vue";
import Loading from "./index.vue";

type LoadingOptions = {
    target?: string | HTMLElement; // 可指定挂载的目标元素
    text?: string; // 加载文字
    background?: string; // 背景色
    spinner?: boolean; // 是否显示旋转动画
    // 其他你需要的配置项...
};

class LoadingService {
    private instance: any = null;
    private targetEl: HTMLElement | null = null;

    show(options: LoadingOptions = {}) {
        // 如果已经存在实例，先关闭
        if (this.instance) {
            this.hide();
        }

        // 获取目标元素
        this.targetEl = this.getTargetElement(options.target);
        if (!this.targetEl) return;

        // 创建Loading实例
        const app = createApp(Loading);
        this.instance = app.mount(document.createElement("div"));

        // 设置样式确保定位正确
        this.setTargetStyle(this.targetEl);

        // 更新Loading状态
        this.instance.updateLoading({
            show: true,
            description: options.text || "加载中...",
            maskBackground: options.background || "rgba(255, 255, 255, 0.5)",
            rotate: options.spinner !== false,
        });

        // 挂载到DOM
        this.targetEl.appendChild(this.instance.$el);
    }

    hide() {
        if (this.instance && this.targetEl) {
            this.instance.updateLoading({ show: false });
            this.targetEl?.removeChild(this.instance.$el);
            // this.instance.unmount()
            this.instance = null;
            this.targetEl = null;
        }
    }

    private getTargetElement(
        target?: string | HTMLElement
    ): HTMLElement | null {
        if (target instanceof HTMLElement) {
            return target;
        }

        if (typeof target === "string") {
            return document.querySelector(target) as HTMLElement;
        }

        // 默认挂载到body
        return document.body;
    }

    private setTargetStyle(el: HTMLElement) {
        const style = getComputedStyle(el);
        if (["absolute", "fixed", "relative"].indexOf(style.position) === -1) {
            el.style.position = "relative";
        }
    }
}

// 创建单例
const loadingService = new LoadingService();

// 挂载到window对象
declare global {
    interface Window {
        NLoading: LoadingService;
    }
}

window.NLoading = loadingService;

export default loadingService;
